<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>编辑翻译</title>
    <link rel="stylesheet" href="./src/css/layui.css">
    <style>
        body {
            padding: 20px;
            box-sizing: border-box;
        }
        .layui-form-label, .translated-label {
            display: block;
            width: 100%;
            text-align: left;
            font-size: 14px;
            font-weight: normal;
            color: #333;
            margin-bottom: 8px;
            line-height: 1.5;
            padding: 0;
        }
        .layui-input-block, .translated-text-container {
            width: 100%;
            display: block;
            margin: 0;
        }
        .layui-textarea {
            width: 100%;
            height: 150px;
            resize: vertical;
            font-size: 14px;
            line-height: 1.5;
            border: 1px solid #d2d2d2;
            border-radius: 4px;
            padding: 8px;
            box-sizing: border-box;
            margin: 0;
        }
        .save-button-container {
            text-align: center;
            margin-top: 20px;
        }
        .layui-form-item {
            margin-bottom: 20px;
            padding: 0;
        }
        .layui-layer-content {
            font-size: 18px !important;
            color: #009688 !important;
            font-weight: bold !important;
        }
    </style>
</head>
<body>
<div class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label">原文:</label>
        <div class="layui-input-block">
            <textarea class="layui-textarea" readonly id="originalText" style="height: 300px"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="translated-label" id="languageLabel">翻译为 english 的译文:</label>
        <div class="translated-text-container">
            <textarea class="layui-textarea" id="translatedText" style="height: 300px"></textarea>
        </div>
    </div>
    <div class="layui-form-item save-button-container">
        <button class="layui-btn" onclick="saveTranslation()">保存</button>
    </div>
</div>

<script src="./src/layui.js"></script>
<script src="./src/msg.js"></script>
<script src="./translate.service.js"></script>
<script>
    layui.use(['form', 'layer', 'jquery'], function(){
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;

        // 清理文本，移除异常字符
        function cleanText(str) {
            if (!str || typeof str !== 'string') return '';
            return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '')
                .replace(/['‘’][‘’]\s*[)）]/g, '')
                .trim();
        }

        // 解析 URL 参数
        function getQueryParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            return r ? decodeURIComponent(r[2]) : '';
        }

        // 获取 URL 参数
        var urlId = cleanText(getQueryParam('id'));
        var urlLanguage = cleanText(getQueryParam('language'));

        // 从 localStorage 获取数据
        var data = JSON.parse(localStorage.getItem('translateData') || '{}');
        var sessionId = cleanText(data.id || '');
        var sessionLanguage = cleanText(data.language || '');
        var text = cleanText(data.text || '');
        var originalText = cleanText(data.originalText || '');
        var domainParam = cleanText(data.domain || '');

        // 调试：输出参数
        //console.log('URL params:', { urlId, urlLanguage });
        //console.log('Session params:', { sessionId, sessionLanguage, text, originalText, domainParam });

        // 比较 URL 和 localStorage 的 id 和 language
        if (urlId != sessionId || urlLanguage != sessionLanguage) {
            //console.log('Data mismatch:', { urlId, urlLanguage, sessionId, sessionLanguage });
            // 显示加载提示，类似保存成功的风格
            var loadIndex = msg.failure('数据不一致，请刷新后重试');
            setTimeout(function() {
                // 关闭加载提示
                msg.close(loadIndex);
                // 关闭 iframe 弹窗
                var index = layer.getFrameIndex(window.name);
                if (index) {
                    layer.close(index);
                }
            }, 2000); // 延迟 2 秒，与保存成功一致
            return; // 阻止后续逻辑执行
        }

        // 动态设置语言标签
        if (sessionLanguage) {
            $('#languageLabel').text('翻译为 ' + sessionLanguage + ' 的译文:');
        } else {
            $('#languageLabel').text('翻译为未知语言的译文:');
        }

        // 填充数据
        $('#originalText').val(originalText);
        $('#translatedText').val(text);

        // 可选择清除 localStorage 数据
        localStorage.removeItem('translateData');

        // 保存翻译
        window.saveTranslation = function() {
            var updatedText = $('#translatedText').val().trim();
          /*  if (!updatedText) {
                msg.failure('译文不能为空');
                return;
            }*/

            // 显示保存中的加载提示
            var loadIndex = msg.loading('正在保存...');

            var params = {
                token: token,
                originalText: originalText,
                to: sessionLanguage,
                resultText: updatedText,
                domain: domainParam,
                translatetextId:urlId
            };

            //console.log('Saving params:', params);

            request.post(domain + 'admin/cache/setCacheText.json', params, function(result) {
                // 关闭保存中的加载提示
                msg.close(loadIndex);

                if (result.result == 1) {
                    // 显示更新中的加载提示
                    var updateLoadIndex = msg.loading('保存成功，正在更新数据...');
                    setTimeout(function() {
                        try {
                            window.parent.postMessage({
                                type: 'updateTranslation',
                                id: sessionId,
                                language: sessionLanguage,
                                text: updatedText,
                                frameName: window.name,
                                updateLoadIndex: updateLoadIndex
                            }, '*');
                            //console.log('Sent postMessage:', { id: sessionId, language: sessionLanguage, text: updatedText, frameName: window.name, updateLoadIndex });
                        } catch (e) {
                            console.error('Failed to send postMessage:', e);
                            msg.close(updateLoadIndex);
                        }
                    }, 2000);
                } else if (result.result == 0) {
                    msg.failure(result.info || '保存失败'); // 显式处理 result=0，显示 info 或默认错误
                } else {
                    msg.failure('API 返回异常，请重试'); // 处理其他意外 result 值
                }
            });
        };
    });
</script>
</body>
</html>